import Vue from 'vue'
import Vuex from 'vuex'
import { Toast } from 'vant';
Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        carArr:JSON.parse(localStorage.getItem('car') || '[]')
    },
    mutations: {
        setCarArr(state, val) {
            let obj = {};
            obj.id = val.id - 0;
            obj.count = val.count - 0;
            obj.price = val.price;
            obj.selected = true;
            var flag = true;
            state.carArr.forEach(item => {
                if(item.id == obj.id) {
                    item.count += val.count;
                    return flag = false 
                }
            })
            Toast.success('已加入购物车');
            if(flag) state.carArr.push(obj);
            localStorage.setItem('car', JSON.stringify(state.carArr))
        },
        add(state, id) {
            state.carArr.forEach(item => {
                if(item.id == id) item.count++;
            })
            
            localStorage.setItem('car', JSON.stringify(state.carArr))
        },
        sub(state, id) {
            state.carArr.forEach(item => {
                if(item.id == id) item.count--;
            })
            localStorage.setItem('car', JSON.stringify(state.carArr))
        }
    },
    actions: {
        
    },
    getters: {
        count (state) {
            var count = 0
            state.carArr.forEach(item=>{
                count+=item.count
            })
            return count
        },

        isEmpty (state) {
            if(state.carArr.length==0){
                return true
            }else{
                return false
            }
        }
    }
})